<template >
    <div>
        <label for="file" class="excelBtn">Excel导入</label>
        <input type="file" id="file" style="display:none" @change="fileChange" ref="excelinputers">
        
    </div>
</template>

<script>
import * as XLSX from 'xlsx/xlsx.mjs'
import * as $ from 'jquery'
export default {
    name: 'excelImport',
    data() {
        return {
            dataSource: []
        }
    },
    props: ['files'],
    mounted() {

    },
    methods: {
        //获取本地文件
        fileChange() {
            let files = document.getElementById('file').files
            //   console.log(files)
            this.fileReader(files[0])
        },
        fileReader(file) {
            //   console.log(file)
            let that = this;
            if (file.length == 0) return;
            if (!/\.xlsx?$/g.test(file.name)) {
                this.$message.warning('上传格式不正确，请上传xls或xlsx格式')
                return;
            }
            //调用本地读取excel的方法
            that.readWorkbookFromLocalFile(file, (workbook) => {
                // console.log(workbook)
                //处理获取到的数据
                that.readWorkbook(workbook)
            })
            setTimeout(() => {
                this.$emit('submitToParent', this.dataSource)
            }, 500)
            
        },
        //封装读取本地的excel文件
        readWorkbookFromLocalFile(file, callback) {
            let reader = new FileReader();
            reader.onload = function(e) {
                let data = e.target.result;
                let workbook = XLSX.read(data, { type: 'binary' });
                if (callback) callback(workbook)
            }
            reader.readAsBinaryString(file);
        },
        //封装处理数据的方法
        readWorkbook(workbook) {
            let sheetNames = workbook.SheetNames; //工作表名称集合
            let worksheet = workbook.Sheets[sheetNames[0]];//这里我们只读取第一张sheet
            let csv = XLSX.utils.sheet_to_csv(worksheet);
            //console.log(csv)
            //把拿到的数据转化为表格并输出
            let rows = csv.split('\n');
            //console.log(rows)  
            let arr = [];
            rows.forEach((row, idx) => {
                let columns = row.split(',');
                columns.unshift(idx + 1);
                arr.push(columns)
            })
            this.dataSource = arr;
            // console.log(arr)
        },

        
    },
}
</script>

<style>
.excelBtn {
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    background: #409eff;
    border: 1px solid #DCDFE6;
    color: #FFF;
    text-align: center;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    outline: 0;
    margin: 0;
    -webkit-transition: .1s;
    transition: .1s;
    line-height: 14px;
    font-weight: 500;
    padding: 12px 20px;
    font-size: 14px;
    border-radius: 4px
}
</style>
